package cn.wolfcode.wolf2w.common.security.aspect;

import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.core.utils.ServletUtils;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.util.RedisKeys;
import org.aspectj.lang.ProceedingJoinPoint;
import cn.wolfcode.wolf2w.common.security.annotation.RateLimit;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


@Aspect
@Component
public class RateLimitAspect {

    @Autowired
    private RedisService redisService;

    @Around("@annotation(rateLimit)")
    public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {

        HttpServletRequest request = ServletUtils.getRequest();
        //防刷验证
        String url = request.getRequestURI().substring(1);
        String ip =  request.getRemoteAddr();
        String key = RedisKeys.BRUSH_PROOF.join(url, ip);
        redisService.setnxCacheObject(key, rateLimit.value(), rateLimit.time(), TimeUnit.SECONDS);
        Long decrement = redisService.decrementCacheObjectValue(key);
        if(decrement < 0){
            throw new RuntimeException("请勿频繁访问谢谢咯");
        }
        return joinPoint.proceed();
    }
}